//
//  PublishCarViewController.m
//  JiongTu
//
//  Created by 杨璟 on 16/3/17.
//  Copyright © 2016年 YSKJ. All rights reserved.
//

//输入框总高度
#define INPUT_H 260
//减去导航栏与状态栏的屏幕高度
#define SCREEN_H [UIScreen mainScreen].bounds.size.height - 64

#import "PublishCarViewController.h"
#import "PassengerTableViewController.h"
#import "JTBaseNaviController.h"
#import "JTProvisionViewController.h"

#import "PublishCar.h"
#import "JTDatePicker.h"
#import "JTLocationPicker.h"
#import "JTTimePicker.h"
#import "JTConst.h"
#import "JTDriverTrip.h"
#import "UIView+Extension.h"
#import "JTUser.h"

#import <AVOSCloud.h>
#import <CoreLocation/CoreLocation.h>
#import <SVProgressHUD.h>

NSString * const KVO_Number = @"numberOfPeople";
NSString * const KVO_StartTF = @"startLocationTF.text";
NSString * const KVO_EndTF = @"destinationTF.text";
NSString * const KVO_Price = @"tripPrice";

@interface PublishCarViewController ()<UITextFieldDelegate, CLLocationManagerDelegate>

@property (nonatomic, strong) NSDictionary *priceDict;
@property (nonatomic, assign) NSUInteger tripPrice;
/**
 *  包含所有控件的滚动视图
 */
@property (weak, nonatomic) IBOutlet UIScrollView *contentScroll;
/**
 *  出发地输入框
 */
@property (weak, nonatomic) IBOutlet UITextField *startLocationTF;
/**
 *  出发地街道输入框
 */
@property (weak, nonatomic) IBOutlet UITextField *startStreetTF;
/**
 *  目的地输入框
 */
@property (weak, nonatomic) IBOutlet UITextField *destinationTF;
/**
 *  出发地街道输入框
 */
@property (weak, nonatomic) IBOutlet UITextField *endStreetTF;
@property (weak, nonatomic) IBOutlet UILabel *priceLabel;
/**
 *  装有时间输入框的view
 */
@property (weak, nonatomic) IBOutlet UIView *timeView;
/**
 *  出发日期输入框
 */
@property (weak, nonatomic) IBOutlet UITextField *dateTF;
@property (weak, nonatomic) IBOutlet UITextField *sTimeTF;

/**
 *  人数显示标签
 */
@property (weak, nonatomic) IBOutlet UILabel *peopleNumber;
/**
 *  总人数
 */
@property (nonatomic, assign) NSUInteger numberOfPeople;
/**
 *  备注信息按钮(1.儿童座椅 2.行李托运 3.无烟车 4.可带宠物 5.可充电 6.有WiFi)
 */
@property (strong, nonatomic) IBOutletCollection(UIButton) NSArray *additionBtn;
/**
 *  同意条款按钮
 */
@property (weak, nonatomic) IBOutlet UIButton *agreeBtn;

/**
 *  键盘附加显示view
 */
@property (nonatomic, strong) UIToolbar *kbAccessory;
/**
 *  『发布车』按钮
 */
@property (weak, nonatomic) IBOutlet UIButton *publishBtn;

@property (nonatomic, strong) CLLocationManager *mgr;

@end

@implementation PublishCarViewController

- (NSDictionary *)priceDict {
    if (!_priceDict) {
        NSString *filePath = [[NSBundle mainBundle] pathForResource:@"Price" ofType:@"plist"];
        _priceDict = [NSDictionary dictionaryWithContentsOfFile:filePath];
    }
    return _priceDict;
}

- (UIToolbar *)kbAccessory {
    if (!_kbAccessory) {
        _kbAccessory = [[UIToolbar alloc] init];
        _kbAccessory.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 44);
        UIBarButtonItem *right = [[UIBarButtonItem alloc] initWithTitle:@"确定"
                                                                  style:UIBarButtonItemStyleDone
                                                                 target:self
                                                                 action:@selector(btnPressed:)];
        UIBarButtonItem *space = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace
                                                                               target:nil
                                                                               action:nil];
        _kbAccessory.items = [NSArray arrayWithObjects:space, right, nil];
    }
    return _kbAccessory;
}

- (CLLocationManager *)mgr {
    if (!_mgr) {
        _mgr = [[CLLocationManager alloc] init];
        _mgr.delegate = self;
        // 设置定位精度
        _mgr.desiredAccuracy = kCLLocationAccuracyNearestTenMeters;
        // 设置过滤器为无
        _mgr.distanceFilter = kCLDistanceFilterNone;
    }
    return _mgr;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.numberOfPeople = 1;
    
    self.dateTF.delegate = self;
    self.dateTF.inputView = [JTDatePicker sharedPicker];
    self.dateTF.inputAccessoryView = self.kbAccessory;
    
    self.sTimeTF.delegate = self;
    self.sTimeTF.inputView = [JTTimePicker sharedPicker];
    self.sTimeTF.inputAccessoryView = self.kbAccessory;
    
    self.startLocationTF.inputView = [JTLocationPicker sharedPicker];
    self.startLocationTF.inputAccessoryView = self.kbAccessory;
    self.destinationTF.inputView = [JTLocationPicker sharedPicker];
    self.destinationTF.inputAccessoryView = self.kbAccessory;
    
    //监听人数的最新值
    [self addObserver:self forKeyPath:KVO_Number options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionInitial context:nil];
    [self addObserver:self forKeyPath:KVO_StartTF options:NSKeyValueObservingOptionNew context:nil];
    [self addObserver:self forKeyPath:KVO_EndTF options:NSKeyValueObservingOptionNew context:nil];
    
    [self.publishBtn addTarget:self action:@selector(publishBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    
    if (self.sameTrip) {
        [self sameFind];
    }
}

- (void)dealloc {
    [self removeObserver:self forKeyPath:KVO_Number];
    [self removeObserver:self forKeyPath:KVO_StartTF];
    [self removeObserver:self forKeyPath:KVO_EndTF];
}

- (void)sameFind {
    self.startLocationTF.text = self.sameTrip.startLocation;
    self.startStreetTF.text = self.sameTrip.startStreet;
    self.destinationTF.text = self.sameTrip.endLocation;
    self.endStreetTF.text = self.sameTrip.endStreet;
    self.dateTF.text = self.sameTrip.time;
    self.sTimeTF.text = self.sameTrip.timeInterval;
    self.numberOfPeople = [self.sameTrip.seatCount unsignedIntegerValue];
}
//- (void)dateChanged:(id)sender {
//    UIDatePicker *picker = (UIDatePicker *)sender;
//    NSDate *selectedDate = picker.date;
//    
//    NSDateFormatter *formatter=[[NSDateFormatter alloc]init];
//    formatter.dateFormat=@"yyyy年MM月dd日";
//    NSString *timeStr=[formatter stringFromDate:selectedDate];
//    NSLog(@"date-----%@",selectedDate);
//    //使用日期格式器可以将时区忽略
//    NSLog(@"timeStr-------%@",timeStr);
//    
//    self.timeTF.text = timeStr;
//    
//    //再次使用时区会将日期格式器的时间加上当前时区时间
////    NSTimeZone *timeZone=[NSTimeZone systemTimeZone];
////    NSInteger seconds=[timeZone secondsFromGMTForDate:selectedDate];
////    NSDate *newDate=[selectedDate dateByAddingTimeInterval:seconds];
////    NSString *newTimeStr=[formatter stringFromDate:newDate];
////    NSLog(@"newDate----%@",newDate);
////    NSLog(@"newTimeStr-------%@",newTimeStr);
//}

- (void)btnPressed:(id)sender {
    
    if (self.startLocationTF.editing) {
        self.startLocationTF.text = [JTLocationPicker sharedPicker].cityAndSubloca;
    } else if (self.destinationTF.editing) {
        self.destinationTF.text = [JTLocationPicker sharedPicker].cityAndSubloca;
    } else if (self.dateTF.editing) {
        NSDate *selectedDate = [JTDatePicker sharedPicker].date;
        
        //使用日期格式器可以将时区忽略
        NSDateFormatter *dateFormatter=[[NSDateFormatter alloc]init];
        dateFormatter.dateFormat=@"yyyy年MM月dd日";
        NSString *dateStr=[dateFormatter stringFromDate:selectedDate];
        self.dateTF.text = dateStr;
        
        NSDateFormatter *timeFormatter=[[NSDateFormatter alloc]init];
        timeFormatter.dateFormat=@"HH时mm分";
        NSString *timeStr = [timeFormatter stringFromDate:selectedDate];
        self.sTimeTF.text = timeStr;
        
        //选择完日期后改变时间选择器内容
        self.sTimeTF.inputView = [JTTimePicker pickerWithDate:selectedDate];
        
    } else if (self.sTimeTF.editing) {
        JTTimePicker *picker = self.sTimeTF.inputView;
        NSDate *selectedDate = picker.date;
        
        NSDateFormatter *formatter=[[NSDateFormatter alloc]init];
        formatter.dateFormat=@"HH时mm分";
        NSString *timeStr=[formatter stringFromDate:selectedDate];
        self.sTimeTF.text = timeStr;
    }
    
    [self.dateTF endEditing:YES];
    [self.sTimeTF endEditing:YES];
    [self.startLocationTF endEditing:YES];
    [self.destinationTF endEditing:YES];
    
}

#pragma mark - 点击发布按钮
- (void)publishBtnClick:(id)sender {
    if ([self.startLocationTF.text isEqualToString:@""]) {
        [SVProgressHUD showInfoWithStatus:@"出发地不能为空"];
    } else if ([self.destinationTF.text isEqualToString:@""]) {
        [SVProgressHUD showInfoWithStatus:@"目的地不能为空"];
    } else if ([self.dateTF .text isEqualToString:@""]) {
        [SVProgressHUD showInfoWithStatus:@"日期不能为空"];
    } else if ([self.sTimeTF.text compare:@"06时00分"] == -1) {
        [SVProgressHUD showInfoWithStatus:@"时间不在范围内"];
    } else if (!self.agreeBtn.isSelected) {
        [SVProgressHUD showInfoWithStatus:@"请同意条款"];
    } else if (self.tripPrice == 0) {
        [SVProgressHUD showInfoWithStatus:@"您选择的线路未开通"];
    } else {
        NSMutableString *additionStr = [[NSMutableString alloc] init];
        for (UIButton *btn in self.additionBtn) {
            if (btn.selected) {
                [additionStr appendString:btn.titleLabel.text];
                [additionStr appendString:@" "];
            }
        }
        
        JTDriverTrip *oneTrip = [[JTDriverTrip alloc] init];
        oneTrip.startLocation = self.startLocationTF.text;
        oneTrip.startStreet = self.startStreetTF.text;
        oneTrip.endLocation = self.destinationTF.text;
        oneTrip.endStreet = self.endStreetTF.text;
        oneTrip.time = self.dateTF.text;
        oneTrip.timeInterval = self.sTimeTF.text;
        oneTrip.seatCount = @(self.numberOfPeople);
        oneTrip.currentSeatCount = @0;
        oneTrip.driver = [AVUser currentUser];
        oneTrip.price = @(self.tripPrice);
        oneTrip.identity = @"司机";
        oneTrip.start =[self.startLocationTF.text substringToIndex:3];
        oneTrip.end =[self.destinationTF.text substringToIndex:3];
        if (additionStr) {
            oneTrip.remark = additionStr;
        }
        
        if (self.sameTrip) {
            //先删除之前的一单
            AVQuery * query = [AVQuery queryWithClassName:kJTClassJourneyDriver];
            [query whereKey:@"objectId" equalTo:self.sameTrip.objectId];
            [query getFirstObjectInBackgroundWithBlock:^(AVObject *object, NSError *error) {
                [object deleteInBackground];
            }];
            //然后再进行发布
            AVQuery * newTripQuery = [AVQuery queryWithClassName:kJTClassDriver];
            [newTripQuery whereKey:kJTDriverKeyId equalTo:[AVUser currentUser].objectId];
            [newTripQuery getFirstObjectInBackgroundWithBlock:^(AVObject *object, NSError *error) {
                if (object) {
                    [PublishCar driver:object publish:oneTrip];
                } else {
                    [PublishCar firstPublish:oneTrip];
                }
            }];
        } else {
            AVQuery * query = [AVQuery queryWithClassName:kJTClassDriver];
            [query whereKey:kJTDriverKeyId equalTo:[AVUser currentUser].objectId];
            [query getFirstObjectInBackgroundWithBlock:^(AVObject *object, NSError *error) {
                if (object) {
                    [PublishCar driver:object publish:oneTrip];
                } else {
                    [PublishCar firstPublish:oneTrip];
                }
            }];
        }
        
        //    JTBaseNaviController *vc = segue.destinationViewController;
        //    PassengerTableViewController *tvc = vc.topViewController;
        //    tvc.driverTrip = oneTrip;
        
        UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
        PassengerTableViewController *vc = [sb instantiateViewControllerWithIdentifier:@"passTableVC"];
        vc.driverTrip = oneTrip;
        JTBaseNaviController *navi = [JTBaseNaviController navigationControllerWithRootViewController:vc];
        [self presentViewController:navi animated:YES completion:^{
            [self.navigationController popToRootViewControllerAnimated:NO];
        }];
    }
}

#pragma mark - UITextFieldDelegate
- (void)textFieldDidBeginEditing:(UITextField *)textField {
    //文本框最下端在当前屏幕中的位置
    CGFloat textMaxY = CGRectGetMaxY(textField.frame) + CGRectGetMinY(self.timeView.frame) - self.contentScroll.contentOffset.y;
    //如果被键盘遮挡
    if (textMaxY > (SCREEN_H - INPUT_H)) {
        CGFloat nowY = self.contentScroll.contentOffset.y;
        //上移的高度
        nowY += textMaxY - (SCREEN_H - INPUT_H);
        [UIView animateWithDuration:0.25 animations:^{
            self.contentScroll.contentOffset = CGPointMake(0, nowY);
        }];
    }
}

#pragma mark - CLLocationManagerDelegate
//- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
//    
//    NSLog(@"location:%@", locations);
//    
//    // 获取当前所在的地理位置街道
//    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
//    //根据经纬度反向地理编译出地址信息
//    [geocoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray *array, NSError *error){
//        if (array) {
//            CLPlacemark *placemark = [array objectAtIndex:0];
//        }
//        else if (error == nil && [array count] == 0) {
//            NSLog(@"No results were returned.");
//        }
//        else if (error != nil) {
//            NSLog(@"An error occurred = %@", error);
//        }
//    }];
//    
//    [manager stopUpdatingLocation];
//}

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
    // 获取当前所在的地理位置街道
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    //根据经纬度反向地理编译出地址信息
    [geocoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray *array, NSError *error){
        if (array) {
            CLPlacemark *placemark = [array objectAtIndex:0];
            NSLog(@"%@", placemark.addressDictionary);
            NSString *city = [NSString stringWithFormat:@"%@%@", placemark.addressDictionary[@"City"], placemark.addressDictionary[@"SubLocality"]];
            self.startLocationTF.text = city;
            NSString *street = [NSString stringWithFormat:@"%@", placemark.addressDictionary[@"Street"]];
            self.startStreetTF.text = street;
        }
        else if (error == nil && [array count] == 0) {
            NSLog(@"No results were returned.");
        }
        else if (error != nil) {
            NSLog(@"An error occurred = %@", error);
        }
    }];
    
    [manager stopUpdatingLocation];
}

#pragma mark - 按钮监听
- (IBAction)plusClick:(id)sender {
    if (self.numberOfPeople < 4) {
        self.numberOfPeople++;
    }
}

- (IBAction)minusClick:(id)sender {
    if (self.numberOfPeople > 1) {
        self.numberOfPeople--;
    }
}

- (IBAction)additonClick:(id)sender {
    UIButton *btn = sender;
    NSLog(@"addtionTag:%d", btn.tag);
    btn.selected = !btn.isSelected;
}

- (IBAction)agreeBtnClick:(id)sender {
    UIButton *btn = sender;
    btn.selected = !btn.isSelected;
}

- (IBAction)provisionClick:(id)sender {
    UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    JTProvisionViewController *proVC = [sb instantiateViewControllerWithIdentifier:@"provision"];
    proVC.provisionName = @"Provision_Driver";
    JTBaseNaviController *navi = [JTBaseNaviController navigationControllerWithRootViewController:proVC];
    [self presentViewController:navi animated:YES completion:nil];
}


- (IBAction)startLoca:(id)sender {
    
    self.startLocationTF.text = @"正在定位中";
    
    [self.mgr requestAlwaysAuthorization];
    [self.mgr startUpdatingLocation];
}


#pragma mark - KVO
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
    
    if ([keyPath isEqualToString:KVO_Number]) {
        self.peopleNumber.text = [NSString stringWithFormat:@"%@位", change[@"new"]];
        self.priceLabel.text = [NSString stringWithFormat:@"%lu元", ([change[@"new"] unsignedIntegerValue] * self.tripPrice)];
    }
    
    if ([keyPath isEqualToString:KVO_Price]) {
        self.priceLabel.text = [NSString stringWithFormat:@"%@元", change[@"new"]];
    }
    
    if ([keyPath isEqualToString:KVO_EndTF]) {
        [self calculatePrice:change[@"new"] withOtherLocation:self.startLocationTF.text number:self.numberOfPeople];
    } else if ([keyPath isEqualToString:KVO_StartTF]) {
        NSLog(@"%@", change);
        [self calculatePrice:change[@"new"] withOtherLocation:self.destinationTF.text number:self.numberOfPeople];
    }
    
}

/**
 *  计算两个文本框中位置的价钱
 */
- (void)calculatePrice:(NSString *)location withOtherLocation:(NSString *)other number:(NSUInteger)number {
    //正在编辑文本框的城市
    NSString *startCity = [NSString string];
    if (![location isEqualToString:@""]) {
        startCity = [location substringToIndex:3];
    }
    //另外一个文本框的城市
    NSString *endCity = [NSString string];
    if (![other isEqualToString:@""]) {
        endCity = [other substringToIndex:3];
    }
    //以另外一个文本框的成都为起点
    if ([endCity isEqualToString:@"成都市"]) {
        //如果正在编辑的文本框存在对应的项目
        if (self.priceDict[startCity]) {
            if (self.priceDict[location]) {
                self.tripPrice = [self.priceDict[location] unsignedIntegerValue];
                self.priceLabel.text = [NSString stringWithFormat:@"%u元", (self.tripPrice * number)];
            } else {
                self.tripPrice = [self.priceDict[startCity] unsignedIntegerValue];
                self.priceLabel.text = [NSString stringWithFormat:@"%u元", (self.tripPrice * number)];
            }
        } else {
            self.tripPrice = 0;
            self.priceLabel.text = [NSString stringWithFormat:@"%u元", (self.tripPrice * number)];
        }
    //以正在编辑的文本框的成都为起点
    } else if ([startCity isEqualToString:@"成都市"]) {
        if (self.priceDict[endCity]) {
            if (self.priceDict[other]) {
                self.tripPrice = [self.priceDict[other] unsignedIntegerValue];
                self.priceLabel.text = [NSString stringWithFormat:@"%u元", (self.tripPrice * number)];
            } else {
                self.tripPrice = [self.priceDict[endCity] unsignedIntegerValue];
                self.priceLabel.text = [NSString stringWithFormat:@"%u元", (self.tripPrice * number)];
            }
        } else {
            self.tripPrice = 0;
            self.priceLabel.text = [NSString stringWithFormat:@"%u元", (self.tripPrice * number)];
        }
    //两个文本框都不以成都为起点，则费用为0
    } else {
        self.tripPrice = 0;
        self.priceLabel.text = [NSString stringWithFormat:@"%u元", (self.tripPrice * number)];
    }
}

@end
